package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile) {
       //检测参数
   if(multipartFile==null||multipartFile.getSize()==0){
       return ResponseResult.errorResult(500,"图片不能为空");
   }
        String fileName = UUID.randomUUID().toString().replaceAll("-", "");
        String originalFilename = multipartFile.getOriginalFilename();
        String postfix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //上传图片到minio
        try {
            fileStorageService.uploadImgFile("",fileName+postfix,multipartFile.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //上传图片到数据库
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUrl(fileName);
        wmMaterial.setId(WmThreadLocalUtil.getUser().getId());
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);
        //返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /*
    *
    * 查询列表
    * */
    @Override
    public ResponseResult findList(WmMaterialDto wmMaterialDto) {

        //参数检测
        wmMaterialDto.checkParam();

        //分页查询
        Page page = new Page(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        //根据作者id查询
        wrapper.eq(WmMaterial::getId, WmThreadLocalUtil.getUser().getId());
        //根据时间倒叙查询
        wrapper.orderByDesc(WmMaterial::getCreatedTime);
        Page page1 = page(page, wrapper);

        //查询列表
        //返回结果
      ResponseResult responseResult=  new ResponseResult(wmMaterialDto.getPage(),(int)page1.getTotal());
        return responseResult;
    }
}
